/** BO SharedRoom ViewModel */

/**
 * mapped attribute in JSON from Server
 * Will contain InfraVO To/From Server
 */
var MappedSharedInfraVO = function(data, fromServer) {
	var self = this;
	console.log("data.aypId :: ", data.aypId);
	this.aypId = ko.observable(data.aypId || "");
	console.log("this.aypId() :: ", this.aypId());
	this.sectionId = ko.observable(data.sectionId || "");
	self.infraIds = ko.observableArray([]);
	console.log("data.infraIds :: ", data.infraIds);
	if (data.infraIds) {

		var mappedData = jQuery.map(data.infraIds, function(item) {
			return new InfraIdVO(item);
		});
		self.infraIds(mappedData);
	};
	console.log("self.infraIds() :: ", self.infraIds());
};

var SharedRoomViewModel = function() {
	var self = this;
	////////////////// BO USED /////////////////////////////////////////////////
	self.availableInfraVOArray = ko.observableArray([]);
	self.mappedSharedInfraVO = ko.observable();

	self.selectedInfraVO = ko.observable().extend({
		required : {
			message : ' '
		}
	});

	self.onComboChange = function() {
		//console.log("onComboChange -------------------------------------- \n");
		//self.selectedInfraVO().infraId();
		//console.log("self.selectedInfraVO() :: ", self.selectedInfraVO());
		if (self.selectedInfraVO()) {
			self.selectedInfraVO().isShared(true);
			console.log("self.mySharedInfraVOArray() :: ", self.mySharedInfraVOArray());
			console.log("self.notSharedInfraVOArray() :: ", self.notSharedInfraVOArray());
		};

	};
	self.removeRoom = function(availableInfraVO) {
		console.log("removeRoom availableInfraVO ", availableInfraVO);
		availableInfraVO.isShared(false);
	};

	/**
	 * Init called from initial Controller
	 * after applybinding
	 */
	self.init = function() {
		console.log("ayp_sharedRoom.js self.init  :: ");
		self.getSchoolCERooms(aypId, sectionId);
	};

	/**
	 * set the Shared Rooms As Selected to corresponding VO
	 * in the begining only
	 */
	self.setIsShared = function() {
		ko.utils.arrayForEach(self.availableInfraVOArray(), function(infraVO) {
			for (var i = 0; i < self.mappedSharedInfraVO().infraIds().length; i++) {
				var infraIdVO = self.mappedSharedInfraVO().infraIds()[i];
				//infraVO.isShared(false);
				if (infraIdVO.infraId() == infraVO.infraId()) {
					//console.log(i, " :: matched :: infraVO.infraId() :: ", infraVO.infraId());
					infraVO.isShared(true);
				};
			};
		});
	};
	/**
	 * Used for Combo binding
	 */
	self.notSharedInfraVOArray = ko.computed(function() {
		var returnArray = [];
		ko.utils.arrayForEach(self.availableInfraVOArray(), function(infraVO) {
			if (!infraVO.isShared()) {
				returnArray.push(infraVO);
			};
		});
		//console.log("test1 notSharedInfraVOArray returnArray :: ", returnArray);
		return returnArray;
	});

	/**
	 * Used for Displaying as Shared in the right Boxes.
	 */
	self.mySharedInfraVOArray = ko.computed(function() {
		var returnArray = [];
		ko.utils.arrayForEach(self.availableInfraVOArray(), function(infraVO) {
			//console.log(infraVO.title(), " : test1 1 infraVO.isShared() :: ", infraVO.isShared());
			if (infraVO.isShared()) {
				returnArray.push(infraVO);
			};
		});
		//console.log("test1 1 mySharedInfraVOArray returnArray :: ", returnArray);
		return returnArray;
	});

	/**
	 * Save the data to Server
	 */
	self.saveDataToServer = function(mySaveData) {
		$.ajax({
			url : baseOperationUrl + "saveShareCERooms",
			type : "post",
			data : {
				savedata : mySaveData
			},
			success : function(result) {
				var jsonData = ko.mapping.toJSON(result);
				console.log("jsonData :: ", jsonData);
				if ( typeof (result) == "object") {
					console.log("saveDataToServer result :: ", result);
					self.openSavedConfirmDialog("Save", "Rooms Saved Successfully");
				} else {
					console.log("has a failled message :: ");
					self.openSavedConfirmDialog("Save Error !!!", "Rooms could not be saved.");
				};
			},
			error : function(jqXHR, textStatus, errorThrown) {
				console.log("Error", textStatus);
				self.openSavedConfirmDialog("Save Error !!!", "Rooms could not be saved.");
			}
		});
	};

	//http://p1392:8080/group/karnatak-add/academic-year?p_p_id=AYPManagement_WAR_ceportaltestedge&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_AYPManagement_WAR_ceportaltestedge_Operation=getSchoolCERooms
	/**
	 * Get single question data.
	 */
	self.getSchoolCERooms = function(myAypId, mySectionId) {
		console.log("myAypId, mySectionId :: ", myAypId, mySectionId);
		console.log(baseOperationUrl + " \n 111 getSchoolCERooms -----inside getSchoolCERooms");
		$.ajax({
			url : baseOperationUrl + "getSchoolCERooms",
			type : "post",
			data : {
				aypId : myAypId,
				sectionId : mySectionId
			},
			success : function(result) {
				var jsonData = ko.mapping.toJSON(result);
				console.log("getSchoolCERooms result.available :: ", result.available);
				var mappedData = jQuery.map(result.available, function(item) {
					return new AvailableInfraVO(item);
				});
				self.availableInfraVOArray(mappedData);
				if (result.mapped) {
					var jsObj = JSON.parse(result.mapped);
					console.log("getSchoolCERooms jsObj :: ", jsObj);
					self.mappedSharedInfraVO(new MappedSharedInfraVO(jsObj));
				} else {
					console.log("myAypId :: ", myAypId);
					self.mappedSharedInfraVO(new MappedSharedInfraVO({
						aypId : myAypId,
						sectionId : mySectionId,
						infraIds : []
						// infraIds : [{
						// infraId : "infra-ce45cfdb-dc82-4b19-a924-1a90428844c9"
						// }]
					}));
				};
				console.log("getSchoolCERooms self.mappedSharedInfraVO() :: ", self.mappedSharedInfraVO());

				self.setIsShared();

				//console.log("jsonData :: ", jsonData);
			},
			error : function(jqXHR, textStatus, errorThrown) {
				console.log("getQuestionData getSchoolCERooms Error");
			}
		});
	};
	self.isReadyForSave = ko.observable(false);
	self.mappedSharedInfraVOArrForSave = ko.computed(function() {
		var returnArray = [];
		ko.utils.arrayForEach(self.mySharedInfraVOArray(), function(infraVO) {
			//console.log("infraVO.infraId() :: ", infraVO.infraId());
			var infraVO = new InfraIdVO({
				infraId : infraVO.infraId()
			});
			returnArray.push(infraVO);
		});
		var mappedData = jQuery.map(returnArray, function(item) {
			return new InfraIdVO(ko.toJS(item));
		});
		var preArray = [];
		if (self.mappedSharedInfraVO()) {
			preArray = ko.mapping.toJSON(self.mappedSharedInfraVO().infraIds());
		};
		var newArray = ko.mapping.toJSON(mappedData);
		var readyForSave = preArray != newArray;
		self.isReadyForSave(readyForSave);
		console.log("self.isReadyForSave() :: ", self.isReadyForSave());
		return mappedData;
	});

	/**
	 * Save
	 */
	self.saveSharedRoomData = function() {
		self.mappedSharedInfraVO().infraIds(self.mappedSharedInfraVOArrForSave());
		console.log("saveSharedRoomData infraIds obj :: ", self.mappedSharedInfraVO().infraIds());
		var mapping = {
			'ignore' : ["errors"]
		};
		var saveDataStr = ko.mapping.toJSON(self.mappedSharedInfraVO(), mapping);
		console.log("saveDataStr :: ", saveDataStr);
		self.saveDataToServer(saveDataStr);
	};

	////////////////// EO USED /////////////////////////////////////////////////
	self.myTitle = ko.observable("Some myTitle !");
	self.myDesc = ko.observable("Some myDesc !!!");

	self.isSaveDialogOpen = ko.observable(false);
	self.openSaveDialog = function() {
		this.isSaveDialogOpen(true);
	};
	self.closeSaveDialog = function() {
		this.isSaveDialogOpen(false);
	};

	/**
	 * after Save confirmation Dialog
	 */
	self.isSavedConfirmDialogOpen = ko.observable(false);
	self.openSavedConfirmDialog = function(title, desc) {
		self.myTitle(title);
		self.myDesc(desc);
		this.isSavedConfirmDialogOpen(true);
	};
	self.closeSavedConfirmDialog = function() {
		this.isSavedConfirmDialogOpen(false);
	};
};

/**
 * InfraIdVO To Server
 */
var InfraIdVO = function(data) {
	var self = this;
	//console.log("2 InfraIdVO data.infraId :: ", data.infraId);
	self.infraId = ko.observable(data.infraId || "");
};

/**
 * InfraVO Got from Server
 */
var AvailableInfraVO = function(data) {
	var self = this;
	//console.log("1 InfraVO data :: ", data);
	this.schoolId = ko.observable(data.schoolId || "");
	this.title = ko.observable(data.title || "");
	this.parentId = ko.observable(data.parentId || "");
	this.infraId = ko.observable(data.infraId || "");
	this.infraDesc = ko.observable(data.infraDesc || "");
	this.infraType = ko.observable(data.infraType || "");
	this.isShared = ko.observable(data.isShared || "");
};
ko.utils.extend(SharedRoomViewModel.prototype, {
	//select an item and make a copy of it for editing
	selectItem : function(item) {
	},
	loadMyRooms : function(item) {
		console.log("loadMyRooms :: ");
		this.loadRoomsList();
	},
	selectItemClassRoom : function(item) {
	},

	selectItemAssign : function(item) {

	},

	//just throw away the edited item and clear the selected observables
	revertItem : function() {
	}
});

// attach the .compare method to Array's prototype to call it on any array
Array.prototype.compareWithArray = function(array) {
	// if the other array is a falsy value, return
	if (!array)
		return false;

	// compare lengths - can save a lot of time
	if (this.length != array.length)
		return false;

	for (var i = 0, l = this.length; i < l; i++) {
		// Check if we have nested arrays
		if (this[i] instanceof Array && array[i] instanceof Array) {
			// recurse into the nested arrays
			if (!this[i].compare(array[i]))
				return false;
		} else if (this[i] != array[i]) {
			// Warning - two different object instances will never be equal: {x:20} != {x:20}
			return false;
		}
	}
	return true;
};
// ====================================================================== EO new Model implementation //////////////
/**
 * EO Tab6 ViewModel
 */